package datastructure.linkedlist;

/**
 * 双向链表
 * @author lbw
 */
public class LinkedListDemo {
    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);

        LinkedList list = new LinkedList();
        list.add(node1);
        list.add(node2);
        list.add(node3);
        list.add(node4);
        list.show();
    }
}


class Node{
    public int no;
    public Node next;
    public Node pre;

    public Node(int no) {
        this.no = no;
    }

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                '}';
    }
}

class LinkedList{
    private Node head = new Node(0);
    private int size;

    /**
     * 添加节点
     * @param node
     */
    public void add(Node node){
        Node cur = head;
        while (cur.next != null){
            cur = cur.next;
        }
        cur.next = node;
        node.pre = cur;
        size++;
    }

    /**
     * 删除节点
     * @param index 要删除第几个
     */
    public void delete(int index){
        if (index >= size){
            System.out.println("下标越界");
            return;
        }
        Node cur = head.next;
        for (int i = 0; i < index; i++){
            cur = cur.next;
        }
        //将要被删除节点的上一个节点的next指向被删除节点的next
        cur.pre.next = cur.next;
        //将要被删除节点的下一个节点的pre指向被删除节点的pre
        cur.next.pre = cur.pre;
        size--;
    }

    /**
     * 获取
     * @param index
     * @return
     */
    public Node get(int index){
        if (index >= size){
            throw new ArrayIndexOutOfBoundsException();
        }
        Node cur = head.next;
        for (int i = 0; i < index; i++){
            cur = cur.next;
        }
        return cur;
    }


    public void show(){
        Node cur = head.next;
        for (int i = 0; i < size; i++) {
            System.out.println(cur);
            cur = cur.next;
        }
    }
}
